import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Popconfirm } from 'antd';
import { history } from 'umi';
import React, { useState, useRef } from 'react';
import { ModalForm, ProFormDigit } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { list, removeArticle, updateShareAndView, updateTop } from './service';
import type { TableListItem, TableListPagination } from './data';

const TableList: React.FC = () => {
  const [modalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<Object>({});
  const actionRef = useRef<ActionType>();
  const handleTop = async (record: API.RuleListItem[]) => {
    const hide = message.loading('正在处理');
    let item = { id: record.id };
    item.isTop = record.isTop == 0 ? 1 : 0;
    try {
      const response = await updateTop(item);
      if (response.code == 200) {
        message.success('处理成功,即将刷新');
      } else {
        message.error('处理失败!');
      }
      hide();
      actionRef.current ?.reloadAndRest ?.();
    } catch (error) {
      hide();
      message.error('处理失败');
      return false;
    }
  };

  /** 国际化配置 */

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '文章ID',
      dataIndex: 'id',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '文章',
      dataIndex: 'title',
    },
    {
      title: '封面',
      dataIndex: 'cover',
      hideInSearch: true,
      render: (text, _, index) => {
        console.log("text------",text);
        if (text != null &&text != '-') {
          let url = 'http://oss.yizuoyiyou.com.cn' + text;
          return <img src={url} height={'55px'} width={'55px'} />;
        }

      },
    },
    {
      title: '类型',
      dataIndex: 'channelName',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '阅读量',
      dataIndex: 'viewNum',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '点赞量',
      dataIndex: 'likeNum',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '置顶状态',
      dataIndex: 'isTop',
      width: '100px',
      hideInForm: true,
      hideInSearch: true,
      render: (text, _, index) => {
        return text > 0 ? '已置顶' : '';
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="eidt"
          onClick={() => {
            history.push('/article/article-detail?id=' + record.id);
          }}
        >
          编辑
        </a>,
        <Popconfirm key="delete" title="是否要删除此行？" onConfirm={() => handleRemove(record.id)}>
          <a>删除</a>
        </Popconfirm>,
        <a
          key="update"
          onClick={(e) => {
            e.preventDefault();
            setCurrentRow(record);
            handleModalVisible(true);
          }}
        >
          更新数据
        </a>,
        <Popconfirm
          key="top"
          title={record.isTop == 0 || record.isTop == null ? '确定要置顶吗?' : '确定要取消置顶吗?'}
          onConfirm={() => handleTop(record)}
        >
          <a>{record.isTop == 0 || record.isTop == null ? '置顶' : '取消置顶'}</a>
        </Popconfirm>,
      ],
    },
  ];

  /**
   * 删除节点
   *
   * @param selectedRows
   */

  const handleRemove = async (id: Number) => {
    const hide = message.loading('正在删除');
    try {
      await removeArticle({
        key: id,
      });
      hide();
      message.success('删除成功，即将刷新');
      actionRef.current ?.reloadAndRest ?.();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const handleShareAndView = async (record: API.RuleListItem[]) => {
    const hide = message.loading('正在处理');
    try {
      const response = await updateShareAndView(record);
      if (response.code == 200) {
        message.success('处理成功,即将刷新');
        actionRef.current ?.reloadAndRest ?.();
      } else {
        message.error('处理失败!');
      }
      hide();
      return true;
    } catch (error) {
      hide();
      message.error('处理失败');
      return false;
    }
  };

  return (
    <PageContainer>
      {modalVisible ? (
        <ModalForm
          title={'更新数据'}
          width="500px"
          layout="horizontal"
          visible={modalVisible}
          onVisibleChange={handleModalVisible}
          onFinish={async (value) => {
            // value.viewNum = type;
            // value.likeNum = type;
            value.baseArticleId = currentRow.id;
            console.log('value', value);
            let success = await handleShareAndView(value as Object);
            if (success) {
              handleModalVisible(false);
            }
          }}
        >
          <ProFormDigit
            rules={[
              {
                required: true,
                message: '请输入',
              },
            ]}
            label="阅读量"
            width="md"
            min={1}
            name="viewNum"
          />
          <ProFormDigit
            rules={[
              {
                required: true,
                message: '请输入',
              },
            ]}
            label="点赞量"
            width="md"
            min={1}
            name="likeNum"
          />
        </ModalForm>
      ) : null}

      <ProTable<TableListItem, TableListPagination>
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        headerTitle={
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              history.push('/article/article-detail');
            }}
          >
            <PlusOutlined /> 新增文章
          </Button>
        }
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params,
          sorter,
          filter,
        ) => {
          // console.log(params, sorter, filter);
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          let likeQuery = {};
          if (params.title != '') {
            likeQuery.title = params.title;
          }
          let query = {
            pageNum: params.current,
            pageSize: params.pageSize,
          };
          query.likeQuery = likeQuery;
          const msg = await list(query);
          console.log('msg', msg);
          if (msg.code == 200) {
            return {
              data: msg.data.list,
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: msg.message,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: msg.data.total,
            };
          } else {
          }
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

export default TableList;
